import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { Student } from './entities/student.entity';

@Injectable()
export class StudentService {
  constructor(
    @InjectRepository(Student)
    private readonly studentRepo: Repository<Student>,
  ) {}

  async findAll(page: number = 1, pageSize: number = 10): Promise<{
    list: Student[];
    itemCount: number;
    page: number;
    pageSize: number;
    pageCount: number;
  }> {
    const skip = (page - 1) * pageSize;
    const [data, total] = await this.studentRepo.findAndCount({
      skip,
      take: pageSize,
      order: { sno: 'ASC' }
    });
  
    return {
      list: data,
      itemCount: total,
      page,
      pageSize,
      pageCount: Math.ceil(total / pageSize)
    };
  }

  async findOne(sno: string): Promise<Student | null> {
    // console.log(`Finding student by sno: ${sno}`);
    // const student = await this.studentRepo.findOneBy({ sno });
    // if (student) {
    //   console.log(`Found student: ${JSON.stringify(student)}`);
    // } else {
    //   console.warn(`No student found with sno: ${sno}`);
    // }
    // return student;
    return null;
  }

  async testRawQuery(): Promise<Student | null> {
    const queryRunner = this.studentRepo.manager.connection.createQueryRunner();
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    const result = await queryRunner.query('SELECT * FROM S');
    console.log(JSON.stringify(result));
    return result;
  }

  async create(student: Student): Promise<Student> {
    return await this.studentRepo.save(student);
  }

  async update(
    sno: string,
    student: Partial<Student>,
  ): Promise<Student | null> {
    await this.studentRepo.update(sno, student);
    return this.findOne(sno);
  }

  async delete(sno: string): Promise<void> {
    await this.studentRepo.delete(sno);
  }
}
